import DatePicker from "components/antd-compatible/date-picker";
/**
 * triggerTypeOption里默认四种提醒方式，DAY, WEEK, MONTH, ONCE
 * 其他自定义方式{ label: '', value: '', component: 要写完整的node，跟advanceTable里不一样 }
 * 四个默认的关联控件联系不大，可以拆出去，年后拆，新年快乐
 */
import React, { Component, PropTypes } from "react"
import WrapFormItem from "components/wrap-form-item"
import { Form, Checkbox, Radio, Row, Col, Select, Icon, Button, Input,  message, Spin } from 'antd'
import moment from 'moment';
import { messages } from "share/common";
import Condition from "components/condition";
import 'styles/components/template/remind.scss'
import RemindService from 'components/template/remind/remind.service'
const { Item } = Form;
const { If, Else } = Condition;
const { Option } = Select;

@Form.create()
class Remind extends Component {

  componentWillMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  state = {
    value: {},
    loading: false
  };

  componentDidMount() {
    const { id, value } = this.props;
    if (id) {
      this.setState({ loading: true });
      RemindService.getRemindValue({ id }).then(res => {
        this.setState({ value: Object.assign(res.data, value), loading: false });
      }).catch(e => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
    } else {
      this.setState({ value })
    }
  }

  hourOptions = () => {
    let res = [], i = 0;
    for (i; i < 24; i++) {
      let value = (i % 10 === i ? '0' + i : i) + ':00';
      res.push({ label: value, value })
    }
    return res;
  };

  weekOptions = [
    { label: messages('common-1.key446')/*每周一*/, value: 'MON' },
    { label: messages('common-1.key447')/*每周二*/, value: 'TUES' },
    { label: messages('common-1.key448')/*每周三*/, value: 'WED' },
    { label: messages('common-1.key449')/*每周四*/, value: 'THU' },
    { label: messages('common-1.key450')/*每周五*/, value: 'FRI' },
    { label: messages('common-1.key451')/*每周六*/, value: 'SAT' },
    { label: messages('common-1.key452')/*每周日*/, value: 'SUN' },
  ];

  dayOptions = new Array(28).fill('').concat([
    {label: messages('common-1.key453')/*月末倒数第三天*/, value: "-3"},
    {label: messages('common-1.key454')/*月末倒数第二天*/, value: "-2"},
    {label: messages('common-1.key455')/*月末倒数第一天*/, value: "-1"},
  ]);

  triggerWayOptions = [
    { label: messages('common-1.key456')/*即时提醒*/, value: 'now' },
    { label: messages('common-1.key457')/*延时到指定时间提醒*/, value: 'delay' }
  ];

  handleChangeType = e => {
    let key = e.target.value;
    let temp;
    switch (key) {
      case 'DAY':
        temp = { remindTimes: [] };
        break;
      case 'WEEK':
        temp = { remindDays: [], remindTimes: [] };
        break;
      case 'MONTH':
        temp = { remindDate: undefined, remindTimes: [] };
        break;
      case 'ONCE':
        temp = { triggerWay: 'now', remindDateTime: undefined };
        break;
      default:
        temp = {};
        break;
    }
    this.props.form.setFieldsValue({
      remindWarpValue: temp
    });
  };

  renderRemindTimes = () => {
    const { getFieldValue } = this.props.form;
    const { triggerTypeOption } = this.props;
    let key = getFieldValue('triggerType'), res;
    let defaultKeys = ['DAY', 'WEEK', 'MONTH', 'ONCE'];
    if (defaultKeys.includes(key)) {
      res = this.wrapItem(key);
    } else {
      res = triggerTypeOption.find(item => item.value === key).component;
    }
    return res;
  };

  wrapItem = key => {
    return (
      <WrapFormItem>
        {(onChange, timeValue) => this.getDefaultComponent(onChange, timeValue, key)}
      </WrapFormItem>
    )
  };

  handleChangeTimes = (value, onChange, timeValue, index) => {
    let { remindTimes } = timeValue;
    remindTimes[index] = value;
    onChange({
      remindTimes
    })
  };

  handleChangeDays = (value, onChange) => {
    onChange({
      remindDays: value
    })
  };

  handleDelete = (index, onChange, timeValue) => {
    let { remindTimes } = timeValue;
    remindTimes.splice(index, 1);
    onChange({
      remindTimes
    })
  };

  onAddRemindTimes = (onChange, timeValue) => {
    let { remindTimes } = timeValue;
    remindTimes.push('08:00');
    onChange({
      remindTimes
    })
  };

  handleChangeData = (value, onChange) => {
    onChange({
      remindDate: value
    })
  };

  handleChangeMouth = (e, onChange) => {
    onChange({
      remindTimes: [e.target.value]
    })
  };

  handleChangeWay = (value, onChange) => {
    onChange({
      triggerWay: value
    })
  };

  handleChangeRemindDateTime = (value, onChange) => {
    onChange({
      remindDateTime: moment(value).utc().format()
    })
  };

  getDefaultComponent = (onChange, timeValue, key) => {
    let res = (
      <Row gutter={10}>
        {
          timeValue.remindTimes && timeValue.remindTimes.map((item, index) => (
            <Col span={7}>
              <Col span={17}>
                <Select
                  showSearch
                  allowClear={false}
                  value={item}
                  style={{ width: '100%' }}
                  onChange={e => this.handleChangeTimes(e, onChange, timeValue, index)}
                  placeholder={messages('common.select')/*请选择*/}
                  filterOption={(inputValue, option) => option.props.children.indexOf(inputValue) > -1}
                >
                  {this.hourOptions().map(item => <Option key={item.value}>{item.value}</Option>)}
                </Select>
              </Col>
              <Col onClick={() => this.handleDelete(index, onChange, timeValue)} span={7} style={{cursor: 'pointer'}}>
                <Icon type="close-circle-o" style={{color: 'red', fontSize: 16, marginLeft: '10px'}}/>
              </Col>
            </Col>
          ))
        }
        <Col span={8}>
          <Button onClick={() => this.onAddRemindTimes(onChange, timeValue)} type="dashed">
            <Icon type="plus"/>{messages('common.add')/*添加*/}
          </Button>
        </Col>
      </Row>
    );
    switch (key) {
      case 'DAY':
        break;
      case 'WEEK':
        res = (
          <section>
            <Row gutter={10} style={{ margin: '5px 0 10px' }}>
              <Checkbox.Group
                options={this.weekOptions}
                value={timeValue.remindDays}
                onChange={checked => this.handleChangeDays(checked, onChange)}
              />
            </Row>
            {res}
          </section>
        );
        break;
      case 'MONTH':
        res = (
          <Row gutter={10}>
            <Col span={8}>
              <Select
                showSearch
                allowClear={false}
                style={{ width: '100%' }}
                value={timeValue.remindDate}
                onChange={e => this.handleChangeData(e, onChange)}
                placeholder={messages('common.select')/*请选择*/}
                filterOption={(inputValue, option) => option.props.children.indexOf(inputValue) > -1}>
                {this.dayOptions.map((item, index) =>
                  <Option key={index + 1}>{index < 28 ? index + 1 + "号" : item.label}</Option>)}
              </Select>
            </Col>
            <Col span={8}>
              <Input
                suffix={<Icon type={'clock-circle'}/>}
                value={timeValue.remindTimes[0]}
                placeholder={messages('common-1.key225')/*请输入temp2*/}
                onChange={e => this.handleChangeMouth(e, onChange)}
              />
            </Col>
          </Row>
        );
        break;
      case 'ONCE':
        res = (
          <Row>
            <Col span={24}>
              <Radio.Group
                options={this.triggerWayOptions}
                onChange={e => this.handleChangeWay(e.target.value, onChange)}
                value={timeValue.triggerWay}
              />
            </Col>
            {
              timeValue.triggerWay === 'delay' && (
                <Col span={24}>
                  <DatePicker
                    format="YYYY-MM-DD HH:mm"
                    showTime
                    value={timeValue.remindDateTime ? moment(timeValue.remindDateTime) : undefined}
                    onChange={value => this.handleChangeRemindDateTime(value ,onChange)}
                  />
                </Col>
              )
            }
          </Row>
        );
        break;
      default:
        break;
    }
    return res;
  };

  getValue = () => {
    let temp = null;
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        temp = value;
      }
    });
    return temp;
  };

  saveValue = () => {
    const { id } = this.props;
    return new Promise((resolve, reject) => {
      let params = this.getValue();
      if (params) {
        let temp = params.remindWarpValue;
        if (temp.remindTimes && !temp.remindTimes.length) {
          message.error(messages('common-1.key458')/*请填写提醒时间*/);
          reject({});
        } else {
          delete params.remindWarpValue;
          this.setState({ loading: true });
          RemindService.saveRemindValue(Object.assign(params, temp, id ? { id } : {})).then(res => {
            this.setState({ loading: false });
            resolve(res.data.id)
          }).catch(e => {
            this.setState({ loading: false });
            reject(e);
          })
        }
      } else {
        reject({})
      }
    });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    const { remindClientsOption, triggerTypeOption, disabled, hideType, children } = this.props;
    const { value, loading } = this.state;
    return (
      <section>
        <Spin spinning={loading}>
          <If value={remindClientsOption.length}>
            <Item
              {...formItemLayout}
              label={messages('common-1.key459')/*提醒方式*/}
            >
              {getFieldDecorator('remindClients', {
                rules: [{
                  required:true,
                  message: messages('common.can.not.be.empty',{arg1: messages('common-1.key459')/*提醒方式*/})/*{arg1} 不能为空*/
                }],
                initialValue: value.remindClients || []
              })(
                <Checkbox.Group options={remindClientsOption} disabled={disabled} className='validate-checkbox'/>
              )}
            </Item>
          </If>
          <If value={triggerTypeOption.length}>
            <If value={!hideType}>
              <Item
                {...formItemLayout}
                label={messages('common-1.key460')/*提醒类型*/}
              >
                {getFieldDecorator('triggerType', {
                  rules: [{
                    required:true,
                    message: messages('common.can.not.be.empty',{arg1: messages('common-1.key459')/*提醒方式*/})/*{arg1} 不能为空*/
                  }],
                  initialValue: value.triggerType || 'DAY'
                })(
                  <Radio.Group options={triggerTypeOption} disabled={disabled} onChange={this.handleChangeType}/>
                )}
              </Item>
            </If>
            <Else>
              {children}
            </Else>
            <Item
              {...formItemLayout}
              label={messages('common-1.key461')/*提醒时间*/}
            >
              {getFieldDecorator('remindWarpValue', {
                rules: [{
                  required:true,
                  message: messages('common.can.not.be.empty',{arg1: messages('common-1.key461')/*提醒时间*/})/*{arg1} 不能为空*/
                }],
                initialValue: {
                  remindTimes: value.remindTimes || [],
                  remindDays: value.remindDays,
                  remindDate: value.remindDate,
                  remindDateTime: value.remindDateTime,
                  triggerWay: value.triggerWay
                } || { remindTimes: [] }
              })(
                this.renderRemindTimes()
              )}
            </Item>
          </If>
        </Spin>
      </section>
    )
  }

  static propTypes = {
    value: PropTypes.object, // 自定义控件的默认值
    remindTypesOption: PropTypes.array,
    triggerTypeOption: PropTypes.array,
    disabled: PropTypes.bool,
    id: PropTypes.string, //规则id
    hideType: PropTypes.bool
  };

  static defaultProps = {
    value: {},
    hideType: false,
    remindClientsOption: [
      { label: messages('common-1.key462')/*Web+APP推送*/, value: 'app' },
      { label: messages('common-1.key463')/*钉钉*/, value: 'dingtalk' },
      { label: messages('common-1.key464')/*邮件提醒*/, value: 'mail' },
      { label: messages('common-1.key465')/*企业微信*/, value: 'wechat' }
    ],
    triggerTypeOption: [
      { label: messages('common-1.key466')/*日重复提醒*/, value: 'DAY' },
      { label: messages('common-1.key467')/*周重复提醒*/, value: 'WEEK' },
      { label: messages('common-1.key468')/*月重复提醒*/, value: 'MONTH' },
      { label: messages('common-1.key469')/*单次提醒*/, value: 'ONCE' }
    ],
    disabled: false
  }

}

export default Remind
